import { CSSProperties, useEffect, useMemo, useState } from 'react'
import Kaseo from './kaseo/components/Kaseo/Kaseo'
import {appInitFinished} from './KaseoApp'
import KaseoEditor from './kaseo/components/Editor/KaseoEditor'
import { KaseoEditorModel } from './kaseo/editor/KaseoEditorModel'

import './App.css'

const CALC_WIDTH = 390

function SplitAppView(props: {
    editorModel: KaseoEditorModel
}) {
    const [windowHeight, setWindowHeight] = useState(window.innerHeight)
    const [windowWidth, setWindowWidth] = useState(window.innerWidth)
    const [editorWidth, setEditorWidth] = useState(window.innerWidth - CALC_WIDTH)

    const [calcOnly, setCalcOnly] = useState(false)
    const [singlePageMode, setSinglePageMode] = useState(true)

    useEffect(() => {

        function updateLayout() {
            setWindowHeight(window.innerHeight)
            setWindowWidth(window.innerWidth)
            
            if (window.innerWidth < 600) {
                setSinglePageMode(true)
            } else {
                setSinglePageMode(false)
            }
            setEditorWidth(window.innerWidth - CALC_WIDTH)
        }

        function onResize() {
            updateLayout()
        }

        setInterval(() => {
            updateLayout()
        }, 500)

        window.addEventListener('resize', onResize)

        return () => window.removeEventListener('resize', onResize)
    })

    let editorStyle: CSSProperties = {}
    let calcStyle: CSSProperties = {}

    if (singlePageMode) {
        calcStyle.left = window.innerWidth / 2 - 185
        if (calcOnly) {
            editorStyle.display = 'none'
            calcStyle.display = ''
        } else {
            editorStyle.display = ''
            calcStyle.display = 'none'
            editorStyle.width = window.innerWidth
        }
    } else {
        calcStyle.left = window.innerWidth - CALC_WIDTH
        editorStyle.width = window.innerWidth - CALC_WIDTH
    }

    editorStyle.height = windowHeight

    return (
        <>
            <KaseoEditor model={props.editorModel} style={editorStyle}/>
            <Kaseo style={calcStyle}/>

            {
                singlePageMode ? 
                <button className='switch-button' style={{
                    top: windowHeight / 2 - 25,
                    left: calcOnly ? 0 : windowWidth - 12
                }} onClick={() => setCalcOnly(!calcOnly)}>{calcOnly ? '>' : '<'}</button>
                :undefined
            }
        </>
    )
}

function App() {
    /*
    let model = useMemo(() => {
        const model = new KaseoEditorModel()

        return model
    }, [])
     */

    // const [viewMode, setViewMode] = useState(0)

    useEffect(() => {
        appInitFinished()
    })

    return (
        <>
            <Kaseo/>
        </>
    )
}

export default App
